//共享内存使用管道机制实现同步通信
#ifndef __COMM_HPP__
#define __COMM_HPP__

#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <cassert>

using namespace std;

#define Mode 0666
#define Path "./fifo"

//创建管道
class Fifo
{
public:
    Fifo(const string &path = Path) : _path(path)
    {
        umask(0);
        int n = mkfifo(_path.c_str(), Mode);
        if (n == 0)
        {
            cout << "mkfifo success" << endl;
        }
        else
        {
            cerr << "mkfifo failed, errno: " << errno << ", errstring: " << strerror(errno) << endl;
        }
    }
    ~Fifo()
    {
        int n = unlink(_path.c_str());
        if (n == 0)
        {
            cout << "remove fifo file " << _path << " success" << endl;
        }
        else
        {
            cerr << "remove failed, errno: " << errno << ", errstring: " << strerror(errno) << endl;
        }
    }

private:
    string _path; // 文件路径+文件名
};

//通信方法类
class Sync
{
public:
    Sync() : rfd(-1), wfd(-1)
    {   }
    //进程以读方式打开管道文件
    void OpenReadOrDie()
    {
        rfd = open(Path, O_RDONLY);
        if (rfd < 0)
        {
            exit(1);
        }
    }
    //进程以写方式打开管道文件
    void OpenWriteOrDie()
    {
        wfd = open(Path, O_WRONLY);
        if (wfd < 0)
        {
            exit(1);
        }
    }
    //一个进程等待另一个进程写入数据的等待接口
    bool Wait()
    {
        bool ret = true;
        uint32_t c = 0;
        //利用管道机制，若没有发送数据，这里会在read里一直阻塞等待
        ssize_t n = read(rfd, &c, sizeof(uint32_t));
        if (n == sizeof(uint32_t))
        {
            cout << "server wakeup, begin read shm..." << endl;
        }
        else if (n == 0)
        {
            ret = false;
        }
        else
        {
            return false;
        }
        return ret;
    }
    //进程开始读取数据时被唤醒的接口
    void Wakeup()
    {
        uint32_t c = 0;
        //注意：这里没有往管道中写入进程信息，只是利用了管道的同步机制，让写端等待
        ssize_t n = write(wfd, &c, sizeof(c));
        assert(n == sizeof(uint32_t));
        
        cout << "wakeup server..." << endl;
    }
    ~Sync() {}

private:
    int rfd;
    int wfd;
};

#endif